package com.bamboowind.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author cpw
 * @Date 2022/11/3 10:30
 * @Describe: 发布确认高级 生产者
 */
@Slf4j
@RestController
@RequestMapping("/confirm")
public class ConfirmController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMessage/{message}")
    public void sendMessage(@PathVariable String message) {

        CorrelationData correlationData1 = new CorrelationData("1");

        CorrelationData correlationData2 = new CorrelationData("2");

        // 交换机不管是够收到消息的回调方法
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                String id = correlationData != null ? correlationData.getId() : "";
                if (ack) {
                    log.info("交换机已经收到id为:{}的消息", id);
                } else {
                    log.info("交换机没有收到id为:{}的消息，原因是:{}", id, cause);
                }
            }
        });

        // 当消息无法路由的回调方法
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                log.error("消息:{},被交换机:{}退回，退回原因:{},路由key:{}"
                        , new String(returned.getMessage().getBody())
                        , returned.getExchange()
                        , returned.getReplyText()
                        , returned.getRoutingKey());
            }
        });

        rabbitTemplate.convertAndSend("confirm_exchange", "key1", message + "1", correlationData1);
        rabbitTemplate.convertAndSend("confirm_exchange", "key12", message + "2", correlationData2);
        log.info("发送的消息内容为:{}", message);
    }
}
